#include "../include/StopWatch.h"

namespace Polaris_CommonLib {

timespec TimeSpecDiff(timespec start, timespec end)
{
	timespec temp;
	if ((end.tv_nsec-start.tv_nsec)<0) {
		temp.tv_sec = end.tv_sec-start.tv_sec-1;
		temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
	} else {
		temp.tv_sec = end.tv_sec-start.tv_sec;
		temp.tv_nsec = end.tv_nsec-start.tv_nsec;
	}
	return temp;
}

CStopWatch::CStopWatch()
{
    //ctor
    m_ClockID = CLOCK_REALTIME;
}

CStopWatch::CStopWatch(clockid_t a_ClockID)
{
    m_ClockID = a_ClockID;
}

CStopWatch::~CStopWatch()
{
    //dtor
}

//http://stackoverflow.com/questions/275004/c-timer-function-to-provide-time-in-nano-seconds
//http://linux.die.net/man/3/clock_gettime
//http://www.guyrutenberg.com/2007/09/22/profiling-code-using-clock_gettime/
// must link librt.a, in ClockBlocks, add rt in link settings


void CStopWatch::Start()
{
    clock_gettime( m_ClockID, &m_TSStart);
}

void CStopWatch::Stop()
{
    clock_gettime( m_ClockID, &m_TSStop);
}



int CStopWatch::TotalMs()
{
    timespec diff = TimeSpecDiff(m_TSStart,m_TSStop);
    return diff.tv_sec * 1000 + diff.tv_nsec / 1000000;
}



} // End namesapce
